package com.cykj.faceledtv.netty;


import com.cykj.faceledtv.MyApp;
import com.cykj.faceledtv.entity.NettyConstants;
import com.cykj.faceledtv.entity.NettySendMsgModel;
import com.cykj.faceledtv.utils.ByteUtils;
import com.cykj.faceledtv.utils.MacUtils;
import com.google.gson.JsonObject;


import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * netty tcp编码器
 *
 * @author jzh
 * @date 2018/11/06 14:52
 */
public class NettyEncode extends MessageToByteEncoder<NettySendMsgModel> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, NettySendMsgModel model, ByteBuf out) throws Exception {
        switch (model.getType()) {
            case LOGIN:
                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty(NettyConstants.SERVICE_NAME, NettyConstants.LOGIN);
                jsonObject.addProperty(NettyConstants.MAC, MacUtils.getMac());
                JsonObject jsonObject1 = new JsonObject();
                jsonObject1.addProperty("loginId", MyApp.getInstance().mDataManager.getLoginId());
                jsonObject1.addProperty("loginPsw", MyApp.getInstance().mDataManager.getLoginPassword());
                jsonObject1.addProperty("ledType", 1);
                jsonObject.add(NettyConstants.DATA, jsonObject1);
                out.writeBytes(ByteUtils.mergeByteArray(ByteUtils.charToBytes1(NettyConstants.HEAD)
                        , jsonObject.toString().getBytes("UTF-8"), ByteUtils.charToBytes1(NettyConstants.END)));
                break;
            case HEART:
                out.writeBytes(ByteUtils.mergeByteArray(ByteUtils.charToBytes1(NettyConstants.HEAD)
                        , ByteUtils.charToBytes1(NettyConstants.HEART), ByteUtils.charToBytes1(NettyConstants.END)));
                break;
            case DATA:
                out.writeBytes(ByteUtils.mergeByteArray(ByteUtils.charToBytes1(NettyConstants.HEAD)
                        , model.getSendMsg().getBytes("UTF-8"), ByteUtils.charToBytes1(NettyConstants.END)));
                break;
            default:
                break;
        }
    }
}
